<?php

namespace XWAM\Model;

/**
 * 部门数据库模型
 *
 * @since 1.0.0 <2016-1-14> SoChishun <14507247@qq.com> Added.
 */
class DepartmentModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 't_porg_auth_department';

    public function saveRule($departmentId, $rules) {
        $result = $this->where(array('id' => $departmentId))->setField('rules', implode(',', $rules));
        return $this->returnMsg($result);
    }

    public function deleteDepartment($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        /* 判断是否有子项目
          $list = M()->query('select a.title from think_auth_group a inner join think_auth_group b on b.pid=a.id where b.pid in (' . $id . ')');
          $names = false;
          if ($list) {
          foreach ($list as $row) {
          $names.=',' . $row['name'];
          }
          }
          if ($names) {
          return $this->returnMsg(false, '以下项目有子项目,请先转移子项目:' . "\n" . ltrim($names, ','));
          }
         */
        // 判断是否有引用
        $user_department_ids = M('think_auth_group_access')->where(array('group_id' => array('in', $id)))->getField('group_id', true);
        if ($user_department_ids) {
            $names = $this->where(array('id' => array('in', $user_department_ids)))->getField('title', true);
            return $this->returnMsg(false, '以下项目正在被用户使用,无法删除:' . "\n" . implode(',', $names));
        }
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    function getChildIds($id) {
        return $this->base_getChildIds($id);
    }

    /**
     * 
     * @param type $selectOption
     * @param type $dataOption
     * @return type
     */
    function selectTree($selectOption = array(), $dataOption = array()) {
        $selectOption = array_merge(array('field' => 'id, title, pid, code, rules, sort, status, create_time', 'order' => 'sort, id'), $selectOption);
        return $this->baseSelectTree($selectOption, $dataOption);
    }

    /**
     * 
     * @param type $with_member
     * @param type $select_options
     * @param type $data_options
     * @return type
     */
    function selectTreeWithMember($with_member, $select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => "id, title, 'group' as type", 'order' => 'sort, id'), $select_options);
        $list = $this->baseSelectTree($select_options, $data_options);
        if (!$list || 'Y' != $with_member) {
            return $list;
        }
        $aout = array();
        $sql = "select id, user_name as title, 'user' as type from t_porg_user where department_id=%d order by user_name";
        foreach ($list as $row1) {
            if ($row1['children']) {
                $sub2 = array();
                foreach ($row1['children'] as $row2) {
                    if ($row2['children']) {
                        $sub3 = array();
                        foreach ($row2['children'] as $row3) {
                            $list_u3 = $this->query(sprintf($sql, $row3['id']));
                            if ($list_u3) {
                                $row3['children'] = $row3['children'] ? array_merge($row3['children'], $list_u3) : $list_u3;
                            }
                            $sub3[] = $row3;
                        }
                        $row2['children'] = $sub3;
                    }
                    $list_u2 = $this->query(sprintf($sql, $row2['id']));
                    if ($list_u2) {
                        $row2['children'] = $row2['children'] ? array_merge($row2['children'], $list_u2) : $list_u2;
                    }
                    $sub2[] = $row2;
                }
                $row1['children'] = $sub2;
            }
            $list_u1 = $this->query(sprintf($sql, $row1['id']));
            if ($list_u1) {
                $row1['children'] = $row1['children'] ? array_merge($row1['children'], $list_u1) : $list_u1;
            }
            $aout[] = $row1;
        }
        return $aout;
    }

    function selectTreeJson($select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => 'id, title as text', 'order' => 'sort, id'), $select_options);
        return $this->baseSelectTree($select_options, $data_options);
    }

    function saveDepartment() {
        $rules = array(
            array('title', 'require', '名称无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->error);
        }
        $data = xsfn_array_notempty($this->data, array('pid'));
        if (empty($this->id)) {
            unset($data['id']);
            $result = $this->add($data);
        } else {
            if (isset($data['pid']) && $this->id == $this->pid) {
                return $this->returnMsg(false, '父级不能是自己!'); // 2016-8-5 修正
            }
            $result = $this->save($data);
        }
        return $this->returnMsg($result);
    }

    /**
     * 复制部门
     * @return type
     * @since 1.0 <2016-1-14> SoChishun Added.
     */
    function copyDepartment($id) {
        $table = $this->tableName;
        M()->execute("insert into $table (title,pid,`code`,rules,status,site_id) select concat(title,'_new'),pid,`code`,rules,status,site_id from $table where id=$id");
        return $this->returnMsg(true);
    }

    function changeStatus($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    /**
     * 批量更新外键对应的标题
     * @param type $all
     * @since 1.0 2017-3-17 SoChishun Added.
     */
    static function updateForeignTitle($all = false, $id = '') {
        M()->execute("update t_porg_user u left join t_porg_auth_department d on u.department_id=d.id set u.department_title=d.title where " . ($id ? "u.department_id in ($id)" : "u.department_id > 0") . ($all || $id ? '' : " and u.department_title=''"));
    }

}
